package com.hxzy.shop.marketing.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hxzy.shop.common.dto.marketing.req.*;
import com.hxzy.shop.common.dto.marketing.resp.CommissionResp;
import com.hxzy.shop.common.dto.marketing.resp.DistributionDrugResp;
import com.hxzy.shop.constant.AuthConstant;
import com.hxzy.shop.entity.DistributionDrug;
import com.hxzy.shop.entity.DistributionDrugInnerRule;
import com.hxzy.shop.entity.DistributionLevel;
import com.hxzy.shop.entity.Drug;
import com.hxzy.shop.marketing.dto.resp.DistributionDrugListResp;
import com.hxzy.shop.marketing.mapper.DistributionDrugInnerRuleMapper;
import com.hxzy.shop.marketing.mapper.DistributionDrugMapper;
import com.hxzy.shop.marketing.mapper.DistributionLevelMapper;

import com.hxzy.shop.marketing.mapper.DrugMapper;
import com.hxzy.shop.marketing.service.DistributionDrugService;
import com.hxzy.shop.message.DrugChangeMessage;
import com.hxzy.shop.utils.WebUtil;
import com.hxzy.shop.vo.ApiException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
* @author admin
* @description 针对表【distribution_drug】的数据库操作Service实现
* @createDate 2023-08-03 20:00:10
*/
@Service
public class DistributionDrugServiceImpl extends ServiceImpl<DistributionDrugMapper, DistributionDrug>
    implements DistributionDrugService{

    @Resource
    private DistributionLevelMapper distributionLevelMapper;
    @Resource
    private DrugMapper drugMapper;
    @Resource
    private DistributionDrugInnerRuleMapper distributionDrugInnerRuleMapper;
    @Resource
    private DistributionDrugMapper distributionDrugMapper;

    /**
     * 分销药品列表
     * @param req
     * @return
     */
    @Override
    public PageInfo<DistributionDrugListResp> drugList(DistributionDrugPageReq req) {
        if(ObjectUtil.isNotEmpty(req.getClassifiedManagementIds())){
            req.setClassifiedManagementId(req.getClassifiedManagementIds().get(0));
            if(req.getClassifiedManagementIds().size()>1) {
                req.setSonClassifiedManagementId(req.getClassifiedManagementIds().get(1));
            }

        }
        //查询分销药品
        PageInfo<DistributionDrugListResp> pageInfo = PageHelper.startPage(req.getPageNum(), req.getPageSize()).doSelectPageInfo(() -> {
            distributionDrugMapper.distributionDrugList(req.getDrugName(),req.getBarCode(),req.getDrugCode(),req.getClassifiedManagementId(),req.getSonClassifiedManagementId(),req.getPrescriptionDrug());
        });
        List<DistributionDrugListResp> list = pageInfo.getList();
        for (DistributionDrugListResp resp : list) {
            //每个分销药品对应的分销等级佣金
            List<CommissionResp> commissionList = distributionDrugInnerRuleMapper.selectCommissionByDrugId(resp.getDistributionDrugId());
            resp.setCommissionList(commissionList);
        }
        PageInfo<DistributionDrugListResp> page = new PageInfo<>();
        page.setList(list);
        page.setTotal(pageInfo.getTotal());
        return page;
    }



    /**
     * 分销药品未选列表
     *
     * @param req
     * @return
     */
    @Override
    public PageInfo<DistributionDrugResp> noSelectdrugList(DistributionDrugNoSelectReq req) {
        //全部分销药品
        Long[] drugIdList = distributionDrugMapper.selectList(new LambdaQueryWrapper<DistributionDrug>()
                        .eq(DistributionDrug::getDisable, false))
                .stream().map(DistributionDrug::getDrugId).toArray(Long[]::new);
        String drugCode = req.getDrugCode();
        String all = drugCode.replaceAll("\\s*", "");
        String[] split = all.split("/");
        //查询除了分销药品的全部药品
        PageInfo<DistributionDrugResp> pageInfo = PageHelper.startPage(req.getPageNum(), req.getPageSize()).doSelectPageInfo(() -> {
            distributionDrugMapper.selectNoSelectDrug(req.getDrugName(), req.getBarCode(),req.getDrugCode(), req.getParentClassifiedManagementId(),req.getSonClassifiedManagementId(), drugIdList,split);
        });
        return pageInfo;
    }

    /**
     * 编辑分销药品
     *
     * @param req
     * @return
     */
    @Override
    public Object updateDistributionDrug(UpdateDistributionDrugReq req) {
        List<CommissionResp> commissionList = req.getCommissionList();
        for (CommissionResp commissionResp : commissionList) {
            Long levelId = commissionResp.getDistributionLevelId();
            DistributionDrugInnerRule rule = distributionDrugInnerRuleMapper.selectOne(new LambdaQueryWrapper<DistributionDrugInnerRule>()
                    .eq(DistributionDrugInnerRule::getDistributionDrugId, req.getDrugId())
                    .eq(DistributionDrugInnerRule::getDisable,false)
                    .eq(DistributionDrugInnerRule::getDistributionLevelId,levelId));
            rule.setDistributionLevelId(levelId);
            rule.setCommissionRate(commissionResp.getCommissionRate().divide(BigDecimal.valueOf(100),2,BigDecimal.ROUND_FLOOR));
            rule.setUpdateTime(new Date());
            distributionDrugInnerRuleMapper.updateById(rule);
        }
        return true;
    }

    /**
     * 添加分销药品
     *
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Object addDistributionDrug(AddDistributionDrugReq req) {
        String merchantId = WebUtil.getRequest().getHeader(AuthConstant.MERCHANT_ID);
        List<Long> drugIds = req.getDrugId();
        //查询药品的基本信息
        for (Long drugId : drugIds) {
            Drug drug = drugMapper.selectById(drugId);
            if (ObjectUtil.isEmpty(drug)) {
                throw new ApiException(500, "药品不存在");
            }
            //获取全部分销等级
            List<DistributionLevel> levelList = distributionLevelMapper.selectList(new LambdaQueryWrapper<DistributionLevel>()
                    .eq(DistributionLevel::getDisable, false));
            if (ObjectUtil.isEmpty(levelList)) {
                throw new ApiException(500, "请先设置分销等级管理");
            }
            //保存分销药品
            DistributionDrug distributionDrug = new DistributionDrug();
            distributionDrug.setDrugId(drugId);
            distributionDrug.setCreateTime(new Date());
            distributionDrug.setDisable(false);
            distributionDrugMapper.insert(distributionDrug);
            for (DistributionLevel level : levelList) {
                //添加药品与每个等级的关联规则
                DistributionDrugInnerRule rule = new DistributionDrugInnerRule();
                rule.setDistributionDrugId(distributionDrug.getId());
                rule.setCommissionRateStatus(true);
                rule.setCommissionRate(level.getCommissionRate());
                rule.setDistributionLevelId(level.getId());
                rule.setCreateTime(new Date());
                rule.setDisable(false);
                distributionDrugInnerRuleMapper.insert(rule);
            }
            DrugChangeMessage message=new DrugChangeMessage();
            message.setDrugId(drugId);
            message.setMerchantId(Long.parseLong(merchantId));
            message.setChangeType(2);
            message.setState(true);
           // marketingProduct.sendDrugChangeMsg(message);
        }
        return true;
    }

    @Override
    public Object deleteDistributionDrug(DeleteDistributionDrugReq req) {
        //String merchantId = WebUtil.getRequest().getHeader(AuthConstant.MERCHANT_ID);
        //查询药品id
        for (Long drugId : req.getDrugId()) {
            DistributionDrug distributionDrug = this.distributionDrugMapper.selectById(drugId);
            if (ObjectUtil.isEmpty(distributionDrug)){
                throw new ApiException(500,"药品不存在");
            }
            distributionDrug.setDisable(true);
            //逻辑删除分销药
            this.distributionDrugMapper.updateById(distributionDrug);
            //删除分销药关联返利规则
            List<DistributionDrugInnerRule> ruleList = this.distributionDrugInnerRuleMapper.selectList(new LambdaQueryWrapper<DistributionDrugInnerRule>()
                    .eq(DistributionDrugInnerRule::getDistributionDrugId, drugId)
                    .eq(DistributionDrugInnerRule::getDisable, false)
            );
            for (DistributionDrugInnerRule rule : ruleList) {
                rule.setDisable(true);
                this.distributionDrugInnerRuleMapper.updateById(rule);
            }
        }
        //后面就是消息队列暂不完成
        return true;
    }
}




